package com.yusheng.tr.common.core.config;


import cn.hutool.core.date.DatePattern;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.DelegatingWebMvcConfiguration;

import java.text.SimpleDateFormat;
import java.util.List;


@Configuration
@Slf4j
public class JsonConfig extends DelegatingWebMvcConfiguration {

    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {

        log.info("开启json序列化配置");
        MappingJackson2HttpMessageConverter jackson2HttpMessageConverter = new MappingJackson2HttpMessageConverter();
        ObjectMapper objectMapper = new ObjectMapper();
        SimpleModule simpleModule = new SimpleModule();
        simpleModule.addSerializer(Long.class, ToStringSerializer.instance);
        simpleModule.addSerializer(Long.TYPE, ToStringSerializer.instance);
        objectMapper.registerModule(simpleModule);
        objectMapper.setDateFormat(new SimpleDateFormat(DatePattern.NORM_DATETIME_PATTERN));
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        objectMapper.setSerializerFactory(objectMapper.getSerializerFactory().withSerializerModifier(
                new FastJsonSerializerFeatureCompatibleForJackson(SerializerFeature.WriteNullStringAsEmpty,
                        SerializerFeature.WriteNullBooleanAsFalse,
                        SerializerFeature.WriteNullListAsEmpty)));
        jackson2HttpMessageConverter.setObjectMapper(objectMapper);
        converters.add(jackson2HttpMessageConverter);

    }
}
